<?php
// data.php reads data.db database for requested conditions and provides data in JSON or JSONP format.
// Version: 1.3, 2014-02-19
// Created by Piotr Lyczko, http://google.com/+PiotrLyczko
// Licence: GPLv3, https://gnu.org/licenses/gpl.html

ini_set('memory_limit', '256M');

function getUrl() {
	$url  = @( $_SERVER['HTTPS'] != 'on' ) ? 'http://'.$_SERVER['SERVER_NAME'] :  'https://'.$_SERVER['SERVER_NAME'];
	$url .= ( $_SERVER['SERVER_PORT'] !== 80 ) ? ':'.$_SERVER['SERVER_PORT'] : '';
	$url .= $_SERVER['REQUEST_URI'];
	return $url;
}
function convertUrlQuery($query) { 
	if (empty($query)) $params = array('empty'=>'empty');
	else {
		$queryParts = explode('&', $query);
		$params = array();
		foreach ($queryParts as $param) {
			$item = explode('=', $param);
			$values = explode(',',strtolower($item[1]));
			$params[strtolower($item[0])] = $values;
		unset($param);
		}
	}
	return $params; 
}
function getSelect($params,$validselects) {
	if (isset($params['select'])) {
		$selectarray = array();
		for ($i = 0; $i<count($params['select']); $i++) {
			if (in_array($params['select'][$i],$validselects)) array_push($selectarray,$params['select'][$i]);
		}
		if (empty($selectarray)) $select = '*';
		else $select = implode(',',$selectarray);
	} else $select = '*';
	return $select;
}
function paramsToSQLQuery($params) {
	$typearray = array();
	$validtypes = array('measurement','lastmeasurement','smartmeasurement','forecast','alert');
	if (isset($params['type'])) {
		if (in_array('list',$params['type'])) {
			$validselects = array('type','province','provincedesc','county','countydesc','city','citydesc','location','locationdesc','locationtype','long','lat','parameterslist','parametersdesclist','unitslist');
			$select = getSelect($params,$validselects);
			$where = '';
			if (isset($params['items'])) {
				$where = " WHERE ";
				if (in_array('stations',$params['items'])) $where .= "(location IS NOT NULL) OR ";
				if (in_array('cities',$params['items'])) $where .= "(city IS NOT NULL AND location IS NULL) OR ";
				if (in_array('counties',$params['items'])) $where .= "(city IS NULL AND location IS NULL) OR ";
				$where = substr($where,0,-4);
			}
			return "SELECT ".$select." FROM list".$where;
		} else {
			for ($i = 0; $i<count($params['type']); $i++) {
				if (in_array($params['type'][$i],$validtypes)) array_push($typearray,$params['type'][$i]);
			}
		}
	} else $typearray = $validtypes;
	
	$validselects = array('type','province','provincedesc','county','countydesc','city','citydesc','location','locationdesc','long','lat','date','time','timestamp','parameter','parameterdesc','average','value','unit','percentoflimit','caqi','caqiclass','aqi','aqiclass','message');
	$select = getSelect($params,$validselects);
	
	$validparams = array('type','province','county','city','location','date','time','timestamp','parameter','average');
	$paramarray = array();
	foreach ($params as $key=>$param) {
		if (in_array($key,$validparams)) $paramarray[$key] = $param;
	}
	if (empty($paramarray)) $where = '';
	else {
	$where = " WHERE ";
	foreach ($paramarray as $key=>$param) {
		$where .= "(";
		foreach ($param as $value) {
			if (($key === 'time')||($key === 'timestamp')) $where .= $key." = ".$value." OR ";
			else $where .= $key." = '".$value."' OR ";
		}
		$where = substr($where,0,-4);
		$where .= ") AND ";
	}
	$where = substr($where,0,-5);
	}
	
	$query = '';
	foreach ($typearray as $type) {
		$query .= 'SELECT '.$select.' FROM '.$type.$where.' UNION ALL ';
	}
	$query = substr($query,0,-11);
	return $query;
}

// Convert parameters from url to array
$params = convertUrlQuery(parse_url(getUrl(),PHP_URL_QUERY));

// Fetch data from database
try {
	$db = new PDO('sqlite:'.dirname(__FILE__).DIRECTORY_SEPARATOR.'data.db');
	$query = paramsToSQLQuery($params);
	$stmt = $db->prepare($query);
	$stmt->execute();
	$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
	$db = null;
}
catch(PDOException $e) {
	echo $e->getMessage();
}

// Provide data in JSON/JSONP format
header('access-control-allow-origin: *');
if (array_key_exists('callback',$params)) {
	header('content-type: application/javascript; charset=utf-8');
	echo $_GET['callback'].'('.json_encode($result).')';
}
else {
	header('content-type: application/json; charset=utf-8');
	echo json_encode($result);
}
?>
